package my_test.service.impl;


import my_test.dao.AppUserRepository;
import my_test.model.AppUser;
import my_test.model.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by kevin on 12.11.2016.
 */
@Service(value = "UserDetailsServiceImpl")
@Transactional(readOnly = true)
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private AppUserRepository appUserRepository;

    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        AppUser appUser = this.appUserRepository.findByUsername(username);

        if (appUser == null){
            throw new UsernameNotFoundException("user not found");
        }

        List<SimpleGrantedAuthority> authorityList = new ArrayList<SimpleGrantedAuthority>();

        for (Role role : appUser.getRoles()) {
            authorityList.add(new SimpleGrantedAuthority("ROLE_" + role.getRole()));
        }
        return new AppUserDetailsImpl(appUser.getUsername(), appUser.getPassword(), appUser.getStatus(), authorityList);
    }
}
